package com.lalawaimai.plateform.receive;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.sunflower.FlowerCollector;
import com.lalawaimai.palteform.baselib.utils.CommonUtil;
import com.lalawaimai.plateform.bean.JpushMsgBean;
import com.iflytek.cloud.SynthesizerListener;
import com.lalawaimai.plateform.home.HomeActivity;

import cn.jpush.android.api.JPushInterface;

/**
 * 极光推送
 * Created by WaterWood on 2018/6/7.
 */
public class MyReceiver extends BroadcastReceiver {

    private SpeechSynthesizer mTts;
    private String mEngineType = SpeechConstant.TYPE_CLOUD;// 引擎类型
    private String voicer = "xiaoyan"; // 默认发音人
    private int nums = 0;
    private int current = 0;
    private String content;
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        // 初始化合成对象
        this.context = context;
        mTts = SpeechSynthesizer.createSynthesizer(context, mTtsInitListener);
        Bundle bundle = intent.getExtras();
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            // 自定义消息不会展示在通知栏，完全要开发者写代码去处理
            String content = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String title = bundle.getString(JPushInterface.EXTRA_TITLE);
            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Log.i("收到了自定义消息", content);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            String json = bundle.getString(JPushInterface.EXTRA_EXTRA);
            JpushMsgBean jpushMsgBean = new Gson().fromJson(json, JpushMsgBean.class);
            nums = jpushMsgBean.getVoice_play_nums();
            current++;
            content = jpushMsgBean.getVoice_text();
            //语音合成
            FlowerCollector.onEvent(context, "tts_play");
            // 设置参数
            setParam();
            int code = mTts.startSpeaking(content, mTtsListener);
            if (code != ErrorCode.SUCCESS) {
                CommonUtil.showToast(context, "语音合成失败");
            }
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            String json = bundle.getString(JPushInterface.EXTRA_EXTRA);
            JpushMsgBean jpushMsgBean = new Gson().fromJson(json, JpushMsgBean.class);
            if (CommonUtil.isRunningApp(context, "com.lalawaimai.plateform")) {
                Intent intent1 = new Intent(context, HomeActivity.class);
                intent1.putExtra("flag", true);
                intent1.putExtra("orderId", jpushMsgBean.getOrder_id());
                context.startActivity(intent1);
            } else {
                Intent lunch = new Intent();
                lunch.setComponent(new ComponentName("com.lalawaimai.plateform", "com.lalawaimai.plateform.home.HomeActivity"));
                lunch.setAction(Intent.ACTION_VIEW);
                lunch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                lunch.putExtra("flag", true);
                lunch.putExtra("orderId", jpushMsgBean.getOrder_id());
                context.startActivity(lunch);
            }
        } else {

        }
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    /**
     * 参数设置
     *
     * @return
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, "50");
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, "50");
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            Log.i("speak", "begin");
        }

        @Override
        public void onSpeakPaused() {
        }

        @Override
        public void onSpeakResumed() {
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        @Override
        public void onCompleted(SpeechError error) {
            // TODO: 2018/6/8 进行下一次循环
            if (current < nums) {
                int code = mTts.startSpeaking(content, mTtsListener);
                if (code != ErrorCode.SUCCESS) {
                    CommonUtil.showToast(context, "语音合成失败");
                }
                current++;
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }
    };
}
